<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="javascript,attrbute,property," />





  <link rel="alternate" href="/atom.xml" title="前端-洋洋" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="1. 定义Property：属性，所有的HTML元素都由HTMLElement类型表示，HTMLElement类型直接继承自Element并添加了一些属性，添加的这些属性分别对应于每个HTML元素都有下面的这5个标准特性：id，title，lang，dir，className。DOM节点是一个对象，因此，他可以和其他的JavaScript对象一样添加自定义的属性以及方法。property的值可以是">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaScript中的property和attribute的区别">
<meta property="og:url" content="http://html-js.site/2016/05/05/attribute-vs-property/index.html">
<meta property="og:site_name" content="前端-洋洋">
<meta property="og:description" content="1. 定义Property：属性，所有的HTML元素都由HTMLElement类型表示，HTMLElement类型直接继承自Element并添加了一些属性，添加的这些属性分别对应于每个HTML元素都有下面的这5个标准特性：id，title，lang，dir，className。DOM节点是一个对象，因此，他可以和其他的JavaScript对象一样添加自定义的属性以及方法。property的值可以是">
<meta property="og:updated_time" content="2016-06-08T06:13:22.813Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JavaScript中的property和attribute的区别">
<meta name="twitter:description" content="1. 定义Property：属性，所有的HTML元素都由HTMLElement类型表示，HTMLElement类型直接继承自Element并添加了一些属性，添加的这些属性分别对应于每个HTML元素都有下面的这5个标准特性：id，title，lang，dir，className。DOM节点是一个对象，因此，他可以和其他的JavaScript对象一样添加自定义的属性以及方法。property的值可以是">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="http://html-js.site/2016/05/05/attribute-vs-property/"/>

  <title> JavaScript中的property和attribute的区别 | 前端-洋洋 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  



  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?ca98d1db5559cb59848d14443c7fa5dd";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>








  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">前端-洋洋</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">专注于前端</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                JavaScript中的property和attribute的区别
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-05-05T19:02:45+08:00" content="2016-05-05">
              2016-05-05
            </time>
          </span>

          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2016/05/05/attribute-vs-property/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2016/05/05/attribute-vs-property/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="1-定义"><a href="#1-定义" class="headerlink" title="1. 定义"></a>1. 定义</h2><p><b>Property</b>：属性，所有的HTML元素都由HTMLElement类型表示，HTMLElement类型直接继承自Element并添加了一些属性，添加的这些属性分别对应于每个HTML元素都有下面的这5个标准特性：id，title，lang，dir，className。DOM节点是一个对象，因此，他可以和其他的JavaScript对象一样添加自定义的属性以及方法。property的值可以是任何的数据类型，对大小写敏感，自定义的property不会出现在html代码中，只存在js中。</p>
<p><b>Attribute</b>：特性，区别于property，attribute只能是<b>字符串</b>，大小写不敏感，出现在innerHTML中，通过类数组attributes可以罗列所有的attribute。</p>
<h2 id="2-相同之处"><a href="#2-相同之处" class="headerlink" title="2. 相同之处"></a>2. 相同之处</h2><p>标准的 DOM properties 与 attributes 是同步的。公认的（非自定义的）特性会被以属性的形式添加到DOM对象中。如，id，align，style等，这时候操作property或者使用操作特性的DOM方法如getAttribute()都可以操作属性。不过传递给getAttribute()的特性名与实际的特性名相同。因此对于class的特性值获取的时候要传入“class”。</p>
<h2 id="3-不同之处"><a href="#3-不同之处" class="headerlink" title="3. 不同之处"></a>3. 不同之处</h2><ul>
<li>对于有些标准的特性的操作，getAttribute与点号(.)获取的值存在差异性。如href，src，value，        style，onclick等事件处理程序。</li>
<li>href：getAttribute获取的是href的实际值，而点号获取的是完整的url，存在浏览器差异。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;a href=<span class="string">"#"</span>&gt;&lt;/a&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">    <span class="keyword">var</span> a  = <span class="built_in">document</span>.body.children[<span class="number">0</span>]</span><br><span class="line">    a.href = <span class="string">'/'</span></span><br><span class="line">    alert( <span class="string">'attribute:'</span> + a.getAttribute(<span class="string">'href'</span>) ) <span class="comment">// '/'</span></span><br><span class="line">    alert( <span class="string">'property:'</span> + a.href )  <span class="comment">// IE: '/', others: full URL</span></span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>
<p>src的值的获取类似href，不过IE也会返回full URL；</p>
<p>value值同样存在一些 ‘one-way’（单向）同步的内置属性。</p>
<p>例如，input.value 从 attribute 中同步（即 property 从 attribute 中获得同步）</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;input type=<span class="string">"text"</span> value=<span class="string">"markup"</span>&gt;</span><br><span class="line">  &lt;script&gt;</span><br><span class="line">       var input = document.body.children[0];</span><br><span class="line">       input.setAttribute('value', 'new');</span><br><span class="line">       alert( input.value ); // 'new', input.value changed</span><br><span class="line">       alert( input.getAtrribute(value) ); // 'new'</span><br><span class="line">  &lt;/script&gt;</span><br></pre></td></tr></table></figure>
<p>但是 attribute 不能从 property 中获得同步：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;input type=<span class="string">"text"</span> value=<span class="string">"markup"</span>&gt;</span><br><span class="line"> &lt;script&gt;</span><br><span class="line">      var input = document.body.children[0];</span><br><span class="line">      input.value = 'new';</span><br><span class="line">      alert(input.getAttribute('value'));  // 'markup', not changed!</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure></p>
<p>getAttribute获取的是初始值，而点号获取的是初始值或者.value修改后的值,例如当访问者输入了某些字符后，’value’ attribute 在 property 更新后维持了原始值。原始值可以用来检验 input 是否变化，或者重置它。</p>
<p>对于style和onclick等事件处理程序，getAttribute方法访问时会返回字符串，而点号返回的是相应的对象和事件处理函数。</p>
<p>对于input中的checked属性，</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;input type=<span class="string">"checkbox"</span> checked&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">    var input  = document.body.children[0]</span><br><span class="line">    alert( input.checked ) // true</span><br><span class="line">    alert( input.getAttribute('checked') ) // empty string</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
<p>getAttribute获取的是你是实际设置的值。而点号返回的是布尔值。</p>
<h3 id="浏览器兼容性上的差别"><a href="#浏览器兼容性上的差别" class="headerlink" title="浏览器兼容性上的差别"></a>浏览器兼容性上的差别</h3><ul>
<li>在IE&lt;9的浏览器中，可以用点号和getAttribute在相互之间访问自定义属性。</li>
<li>IE&lt;8（包括IE8种的IE7兼容模式），property和attribute相同。因为attribute对大小写不敏感，在这种情况下，用getAttribute访问特性的时候，浏览器会选择第一次出现的值。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">document</span>.body.abba = <span class="number">1</span> <span class="comment">// assign property (now can read it by getAttribute)</span></span><br><span class="line"><span class="built_in">document</span>.body.ABBA = <span class="number">5</span> <span class="comment">// assign property with another case</span></span><br><span class="line"><span class="comment">// must get a property named 'ABba' in case-insensitive way.</span></span><br><span class="line">alert( <span class="built_in">document</span>.body.getAttribute(<span class="string">'ABba'</span>) ) <span class="comment">// 1</span></span><br></pre></td></tr></table></figure>
<h3 id="优先选择property"><a href="#优先选择property" class="headerlink" title="优先选择property"></a>优先选择property</h3><p>在实际应用中，98%的 DOM 操作都是使用 properties。</p>
<p><b>只有两种情形需要使用attributes</b></p>
<ul>
<li>自定义 HTML attributes，因为它并不同步到DOM property。</li>
<li>访问内置的 HTML attributes，这些 attribute 不能从 property 同步过来。例如 INPUT标签的value值。</li>
</ul>
<blockquote><br>参考资料：<br><a href="http://javascript.info/tutorial/attributes-and-custom-properties" target="_blank" rel="nofollow">http://javascript.info/tutorial/attributes-and-custom-properties</a><br></blockquote>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/wechat.jpg" alt="wangyang WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/alipay.jpg" alt="wangyang Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/javascript/" rel="tag">#javascript</a>
          
            <a href="/tags/attrbute/" rel="tag">#attrbute</a>
          
            <a href="/tags/property/" rel="tag">#property</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/05/05/hello-world/" rel="next" title="Hello World">
                <i class="fa fa-chevron-left"></i> Hello World
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/05/10/前端资料汇总/" rel="prev" title="前端资料汇总">
                前端资料汇总 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2016/05/05/attribute-vs-property/"
           data-title="JavaScript中的property和attribute的区别" data-url="http://html-js.site/2016/05/05/attribute-vs-property/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/default_avatar.jpg"
               alt="wangyang" />
          <p class="site-author-name" itemprop="name">wangyang</p>
          <p class="site-description motion-element" itemprop="description">专注于前端</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">15</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">23</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/WangYang-Rex" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/u/2690568063/" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="617418875" target="_blank" title="QQ">
                  
                    <i class="fa fa-fw fa-qq"></i>
                  
                  QQ
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="mailto:617418875@qq.com" target="_blank" title="Mail">
                  
                    <i class="fa fa-fw fa-envelope-o"></i>
                  
                  Mail
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友链
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://http://moshui.site/" title="moxhuis" target="_blank">moxhuis</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://indexof.site/" title="indexof" target="_blank">indexof</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://xiaoqiang730730.github.io/" title="xiaoqiang" target="_blank">xiaoqiang</a>
                </li>
              
            </ul>
          </div>
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-定义"><span class="nav-number">1.</span> <span class="nav-text">1. 定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-相同之处"><span class="nav-number">2.</span> <span class="nav-text">2. 相同之处</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-不同之处"><span class="nav-number">3.</span> <span class="nav-text">3. 不同之处</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#浏览器兼容性上的差别"><span class="nav-number">3.1.</span> <span class="nav-text">浏览器兼容性上的差别</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#优先选择property"><span class="nav-number">3.2.</span> <span class="nav-text">优先选择property</span></a></li></ol></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">wangyang</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"html-js"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    <script src="/vendors/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/js/src/hook-duoshuo.js"></script>
  






  
  

  

  

  

</body>
</html>
